## transform csv file to markdown table
## author: Ruoyan Han

generate_line <- function(
  line_vec  = c()
){
  output <- ""
  for(i in 1:length(line_vec)){
    output <- paste(output, "| ", line_vec[i], " ", sep = "")
  }
  output <- paste(output, "|", sep = "")
  return(output)
}

# generate_line(line_vec = rep(":---:", 4))

show_markdown_table <- function(
  use_file = T,
  file_path = "temp.csv",
  input = data.frame(),
  header = T,
  format = "middle", # middle, left, right
  save = F,
  return_table = F,
  output_name = "",
  table_name = NA
){
  if(use_file){
    input <- read.csv(file = file_path, header = F)
  }
  width <- dim(input)[2]
  length <- dim(input)[1]
  
  if(is.na(table_name)){
    final_output <- ""
  }else{
    final_output <- paste(table_name, "\n\n", sep = "")
  }
  # set start point for main table
  if(header){
    start_point = 1
  }else{
    start_point = 1
  }
  # first row: var name
  if(header){
    final_output <- paste(
      final_output,
      generate_line(line_vec = names(input)),
      "\n", sep = ""
      )
  }else{
    final_output <- paste(
      final_output,
      generate_line(line_vec = paste("V", 1:width, sep = "")),
      "\n", sep = ""
    )
  }
  # second row: format
  if(format == "middle"){
    final_output <- paste(
      final_output,
      generate_line(line_vec = rep(":---:", width)),
      "\n", sep = ""
    )
  }else{
    if(format == "left"){
      final_output <- paste(
        final_output,
        generate_line(line_vec = rep(":---", width)),
        "\n", sep = ""
      )
    }else{
      if(format == "right"){
        final_output <- paste(
          final_output,
          generate_line(line_vec = rep("---:", width)),
          "\n", sep = ""
        )
      }else{
        cat("\n ERROR: WRONG FORMAT INPUT! \n\n")
      }
    }
  }
  ## main table
  for(i in start_point:length){
    final_output <- paste(
      final_output,
      generate_line(line_vec = as.character(input[i,])),
      "\n", sep = ""
    )
  }
  if(save){
    write.table(final_output, 
                file = paste(output_name,
                             Sys.Date(),
                             ".md", sep = ""),
                fileEncoding = "UTF-8",
                sep = "\n", quote = F)
  }
  # cat(final_output)
  if(return_table){
    return(final_output)
  }
  cat("Finished\n")
  return()
}
?write.table()
# setwd("D://TEMP")
# write.csv(PlantGrowth, row.names = T, file = "testmdtable.csv")
# cat(show_markdown_table(file_path = "testmdtable.csv",
#                         header = F,
#                         format = "right",
#                         save = T))
# 
# 
# 
# cat(show_markdown_table(file_path = "testmdtable.csv",
#                         header = T,
#                         format = "middle"))
# 
# final_output <- show_markdown_table(file_path = "testmdtable.csv",
#                                     header = T,
#                                     format = "middle")
